import { ipcMain } from "electron";
import { autoUpdater } from "electron-updater";

export default class AppUpdater {
  constructor(mainWindow) {
    const logger = require("electron-log");
    logger.transports.file.level = "debug";
    // logger.transports.file.maxSize = 1002430; // 10M
    // logger.transports.file.format = "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}";
    // logger.transports.file.resolvePath = () =>
    //   join(app.getPath("appData"), "quick-electron-chat/logs/main1.log");
    autoUpdater.logger = logger;
    autoUpdater.disableWebInstaller = false;
    autoUpdater.autoDownload = false;
    // autoUpdater.checkForUpdatesAndNotify();
    autoUpdater.checkForUpdates();
    ipcMain.handle("update-download", (data) => {
      console.log("update-download-开始下载", data);
      autoUpdater.downloadUpdate();
    });
    autoUpdater.on("error", (error) => {
      logger.error(["on-error-检查更新失败", error]);
      mainWindow.webContents.send("update-error", error);
    });
    autoUpdater.on("update-available", (info) => {
      logger.info("on-update-available-检查到有更新");
      logger.info(info);
      const { version } = info;
      logger.info(`最新版本 ${version}`);
      mainWindow.webContents.send("update-available");
    });
    autoUpdater.on("update-not-available", () => {
      logger.info("on-update-not-available-没有可用更新");
      // mainWindow.webContents.send('update-not-available')
    });
    autoUpdater.on("download-progress", async (progress) => {
      logger.info("on-download-progress-下载进度", progress);
      mainWindow.webContents.send("download-progress", progress);
    });
    autoUpdater.on("update-downloaded", (res) => {
      logger.info("on-update-downloaded-下载完毕,安装更新", res);
      // mainWindow.webContents.send('update-downloaded')
      autoUpdater.quitAndInstall();
    });
  }
}
